package leetCode.competition;

public class Code_5524 {
  public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) {
    if (customers.length == 0) {
      return -1;
    }

    int res = -1;

    int boardNum = 0; // 总共登陆的人的数目
    int runNum = 0; // 总共轮转的次数
    int[] copyCustimers = customers; // 拷贝
    int pStart = 0; // 指向初始位置
    int tmpBoardNum = copyCustimers[pStart] > 4 ? 4 : copyCustimers[pStart]; // 每次登陆的人的数目
    int waitNum = copyCustimers[pStart] > 4 ? copyCustimers[pStart] - 4 : 0; // 等待的数目
    int leaveNum = 0; // 剩余的人的数目
    int Max = -1;

    for (int i = 0; i < copyCustimers.length; i++) {
      leaveNum += copyCustimers[i];
    }

    while (leaveNum > 0) {
      runNum += 1;
      leaveNum -= tmpBoardNum;
      boardNum += tmpBoardNum;
      if (boardingCost * boardNum - runningCost * runNum > Max) {
        Max = boardingCost * boardNum - runningCost * runNum;
        res = runNum;
      }
      copyCustimers[pStart] -= tmpBoardNum;
      if (copyCustimers[pStart] > 0) {
        pStart--;
      }
      pStart++;
      if (runNum < copyCustimers.length) {
        waitNum += copyCustimers[runNum];
      }
      if (pStart < copyCustimers.length) {
        tmpBoardNum = waitNum > 4 ? 4 : waitNum;
        waitNum -= tmpBoardNum;
      }
    }

    return res;
  }
}
